#!/usr/bin/python

import pygame
import game_engine.GameEngine
import Entity
import EntityObserver
import math
import render_engine.RenderEngine

# Spawner which spawns a particular type of monster
class SpawnerEntity(Entity.Entity, EntityObserver.EntityObserver):

    # Obvious
    def __init__(self, name):
        super(SpawnerEntity, self).__init__(name)
        self.m_lastSpawn = 0
        self.m_lastAgroCheck = 0
        self.m_spawning = False
        self.m_spawnCount = 0
        self.m_maxSpawn = 5
        self.m_spawnClass = "game_engine.entity_manager.FollowMonster.FollowMonster"
        self.m_spawnName = "Bob"
        self.m_spawnAnimationFile = "data.CharacterSprite"
        self.m_spawnImageFile = None

    # Called each frame
    def frameUpdate(self, elapsedms, absolutems):
        # Check for agro
        if self.m_lastAgroCheck + 1000 <= absolutems:
            self.checkAgro()
            self.m_lastAgroCheck = absolutems

        # Check for spawning
        if self.m_spawning and self.m_lastSpawn + 5000 <= absolutems and self.m_spawnCount < self.m_maxSpawn:
            self.spawn()
            self.m_lastSpawn = absolutems

    # Check whether we should engage player
    def checkAgro(self):
        # Hack - aggro distance
        playerEntity = game_engine.GameEngine.getGameEngine().getEntityManager().getPlayerEntity()

        # If the player is dead, don't spawn
        if not(playerEntity.isAlive()):
            self.m_spawning=False
            return
        (playerX, playerY) = playerEntity.getPosition()
        distance = math.sqrt(((self.m_positionX - playerX) ** 2) + ((self.m_positionY - playerY) ** 2)) 

        if distance < 8: 
            self.m_spawning=True
        else:
            self.m_spawning=False

    # Spawn a monster
    def spawn(self):
        # TODO: Paramers for what to spawn
        entity = game_engine.GameEngine.getGameEngine().getEntityManager().spawnEntity(self.m_spawnClass, self.m_spawnName, self.getSize(), self.m_spawnAnimationFile, self.m_spawnImageFile, self.getPosition(), render_engine.RenderEngine.RENDER_OBJ_CHARACTER)
        self.m_spawnCount += 1
        entity.addObserver(self)

    # One of our spawn has been killed
    def observeEntityKilled(self, entity, killedByEntity = None):
        self.m_spawnCount += -1


    # Called when an entity attempts to interact with this entity by bumping into it
    def interactBumped(self, otherEntity):
        return False


